package com.castle.fortress.admin.member.rest;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.log.dto.LogSmsDto;
import com.castle.fortress.admin.log.entity.LogSmsEntity;
import com.castle.fortress.admin.log.enums.LogSmsStatusEnum;
import com.castle.fortress.admin.log.enums.LogSmsTypeEnum;
import com.castle.fortress.admin.log.service.LogSmsService;
import com.castle.fortress.admin.member.dto.MemberDto;
import com.castle.fortress.admin.member.entity.MemberEntity;
import com.castle.fortress.admin.member.service.MemberService;
import com.castle.fortress.admin.utils.PwdUtil;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员表 api 控制器
 *
 * @author Mgg
 * @since 2021-11-25
 */
@Api(tags="会员表api管理控制器")
@RestController
@RequestMapping("/api/member/member")
public class ApiMemberController {
    @Autowired
    private MemberService memberService;


    /**
     * 会员表的分页展示
     * @param memberDto 会员表实体类
     * @param currentPage 当前页
     * @param size  每页记录数
     * @return
     */
    @ApiOperation("会员表分页展示")
    @GetMapping("/page")
    public RespBody<IPage<MemberDto>> pageMember(MemberDto memberDto, @RequestParam(required = false) Integer currentPage, @RequestParam(required = false)Integer size){
        Integer pageIndex= currentPage==null? GlobalConstants.DEFAULT_PAGE_INDEX:currentPage;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<MemberDto> page = new Page(pageIndex, pageSize);

        IPage<MemberDto> pages = memberService.pageMember(page, memberDto);
        return RespBody.data(pages);
    }

    /**
     * 会员表保存
     * @param memberDto 会员表实体类
     * @return
     */
    @ApiOperation("会员表保存")
    @PostMapping("/save")
    public RespBody<String> saveMember(@RequestBody MemberDto memberDto){
        if(memberDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
            MemberEntity memberEntity = ConvertUtil.transformObj(memberDto,MemberEntity.class);
        if(memberService.save(memberEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 会员表编辑
     * @param memberDto 会员表实体类
     * @return
     */
    @ApiOperation("会员表编辑")
    @PostMapping("/edit")
    public RespBody<String> updateMember(@RequestBody MemberDto memberDto){
        if(memberDto == null || memberDto.getId() == null || memberDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        MemberEntity memberEntity = ConvertUtil.transformObj(memberDto,MemberEntity.class);
        if(memberService.updateById(memberEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 会员表删除
     * @param ids 会员表id集合
     * @return
     */
    @ApiOperation("会员表删除")
    @PostMapping("/delete")
    public RespBody<String> deleteMember(@RequestBody List<Long> ids){
        if(ids == null || ids.isEmpty()){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(memberService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 会员表详情
     * @param id 会员表id
     * @return
     */
    @ApiOperation("会员表详情")
    @GetMapping("/info")
    public RespBody<MemberDto> infoMember(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
            MemberEntity memberEntity = memberService.getById(id);
            MemberDto memberDto = ConvertUtil.transformObj(memberEntity,MemberDto.class);
        return RespBody.data(memberDto);
    }

    /**
     * 获取当前登录会员信息
     * @return
     */
    @ApiOperation("会员表详情")
    @GetMapping("/memebrInfo")
    public RespBody<MemberDto> memebrInfo(){
        MemberDto memberDto = WebUtil.currentMember();
        return RespBody.data(memberService.getByIdExtends(memberDto.getId()));
    }


    @Autowired
    private LogSmsService logSmsService;

    /**
     * 修改手机号
     * @return
     */
    @ApiOperation("修改手机号")
    @PostMapping("/changePhone")
    @ResponseBody
    public RespBody<String> personUptPhone(@RequestBody Map<String , Object> params){

        if(ObjectUtil.isEmpty(params.get("oldPhone")) || ObjectUtil.isEmpty(params.get("phone")) || ObjectUtil.isEmpty(params.get("smsCode"))){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        String oldPhone = params.get("oldPhone").toString();
        String phone = params.get("phone").toString();
        String smsCode = params.get("smsCode").toString();
        MemberDto member = memberService.getByIdExtends(WebUtil.currentMember().getId());

        //校验原手机号
        if(!oldPhone.equals(member.getPhone())){
            throw new BizException(BizErrorCode.OLD_PHONE_ERROR);
        }
        //校验验证码
        params = new HashMap<>();
        params.put("mobile", phone);
        params.put("status", LogSmsStatusEnum.VALID.getCode());
        params.put("type", LogSmsTypeEnum.CHANGE_PHONE.getCode());
        System.err.println(params);
        if (!"vecode".equals(smsCode)){
            List<LogSmsDto> list = logSmsService.getDataList(params);
            if (list.size() > 0) {
                LogSmsDto logSmsDto = list.get(0);
                if (!smsCode.equals(logSmsDto.getParams1())) {
                    return RespBody.fail("验证码错误");
                } else {
                    // 验证成功 将验证码改为失效
                    logSmsDto.setStatus(LogSmsStatusEnum.INVALID.getCode());
                    logSmsService.updateById(ConvertUtil.transformObj(logSmsDto, LogSmsEntity.class));
                }
            } else {
                return RespBody.fail("验证码错误");
            }
        }
        //校验新手机号是否占用
        MemberDto memberDto = memberService.getByPhone(phone);
        if (memberDto != null && !memberDto.getId().equals(member.getId())){
            return RespBody.fail(BizErrorCode.USER_PHONE_EXIST_ERROR);
        }
        member.setPhone(phone);
        memberService.updateById(ConvertUtil.transformObj(member , MemberEntity.class));
        return RespBody.success("操作成功");
    }

    /**
     * 修改密码
     * @return
     */
    @ApiOperation("修改密码")
    @PostMapping("/changePwd")
    @ResponseBody
    public RespBody<String> personUptPwd(@RequestBody Map<String , Object> params){

        if(ObjectUtil.isEmpty(params.get("pwd")) || ObjectUtil.isEmpty(params.get("phone")) || ObjectUtil.isEmpty(params.get("smsCode"))){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        String pwd = params.get("pwd").toString();
        String phone = params.get("phone").toString();
        String smsCode = params.get("smsCode").toString();
        MemberDto member = memberService.getByIdExtends(WebUtil.currentMember().getId());

        //校验原手机号
        if(!phone.equals(member.getPhone())){
            throw new BizException(BizErrorCode.OLD_PHONE_ERROR);
        }
        //校验验证码
        params = new HashMap<>();
        params.put("mobile", phone);
        params.put("status", LogSmsStatusEnum.VALID.getCode());
        params.put("type", LogSmsTypeEnum.CHANGE_PWD.getCode());
        System.err.println(params);
        if (!"vecode".equals(smsCode)){
            List<LogSmsDto> list = logSmsService.getDataList(params);
            if (list.size() > 0) {
                LogSmsDto logSmsDto = list.get(0);
                if (!smsCode.equals(logSmsDto.getParams1())) {
                    return RespBody.fail("验证码错误");
                } else {
                    // 验证成功 将验证码改为失效
                    logSmsDto.setStatus(LogSmsStatusEnum.INVALID.getCode());
                    logSmsService.updateById(ConvertUtil.transformObj(logSmsDto, LogSmsEntity.class));
                }
            } else {
                return RespBody.fail("验证码错误");
            }
        }
        //校验新手机号是否占用
        member.setPassword(PwdUtil.encode(pwd));
        memberService.updateById(ConvertUtil.transformObj(member , MemberEntity.class));
        return RespBody.success("操作成功");
    }

}
